<script setup lang="ts">
import { ref } from 'vue';

import { Button, message, Modal, Tooltip } from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  acceptOrder,
  approveEarlyCheckOut,
  orderCheckIn,
  orderReject,
} from '#/api';
import { BASE_ICON_URL } from '#/config';

import AgreeCancelModal from './AgreeCancelModal.vue';
import OrderDetailsMain from './OrderDetailsMain.vue';
import RefuseCancelModal from './RefuseCancelModal.vue';
import RefuseEditModal from './RefuseEditModal.vue';

const props = defineProps({
  tabState: {
    type: [String, Number],
    default: '',
  },
  data: {
    type: Object,
    default: () => ({}),
  },
  type: {
    type: String,
    default: '',
  },
  total: {
    type: Number,
    default: 0,
  },
});

const emit = defineEmits(['upOrderData']);

// 更新订单详情数据
const upOrderData = () => {
  emit('upOrderData', props.data?.orderNo || '');
};

// 订单状态的文字以及背景处理 到时候改为实际状态值
const orderStatus = (type: 'bg' | 'text') => {
  let status = props.data?.orderType as 1 | 2 | 3 | 4 | 5 | 6 | 7;
  const orderStatus = props.data?.orderStatus;
  if (orderStatus === 7) {
    status = 5;
  } else if (orderStatus === 31) {
    status = 7;
  } else if (props.type === 'default') {
    status = 6;
  }
  // 确保status是有效值，默认为6（无效状态）
  const validStatus = [1, 2, 3, 4, 5, 6, 7].includes(status) ? status : 6;

  const list = {
    1: { text: '新订', bg: 'bg-primary' },
    2: { text: '修改', bg: 'bg-orange-300' },
    3: { text: '续住', bg: 'bg-blue-300' },
    4: { text: '取消', bg: 'bg-red-400' },
    5: { text: '取消-过时', bg: 'bg-red-400' },
    6: { text: '无效', bg: 'bg-gray-300' },
    7: { text: '拒绝-取消', bg: 'bg-red-400' },
  };
  // 确保访问安全
  return list[validStatus]?.[type] || '';
};

// 是否显示拒绝取消弹窗
const isShowRefuseCancelModal = ref(false);
// 是否显示拒绝修改弹窗
const isShowRefuseEditModal = ref(false);
// 是否显示同意取消订单弹窗
const isShowAgreeCancelModal = ref(false);

// 入住按钮点击事件
const handleCheckIn = () => {
  Modal.confirm({
    title: '平台提示',
    content: '请确认客人已到酒店并完成办理入住手续！',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        await orderCheckIn({
          orderNo: props.data.orderNo,
        });
        upOrderData();
        message.success('操作成功');
      } catch (error) {
        console.error('入住确认失败：', error);
      }
    },
  });
};

// 判断是否显示入住按钮 根据当前日期判断是否大于等于入住日期
const isShowCheckInBtn = () => {
  if (!props.data?.checkInDate) return false;
  const checkInDate = dayjs(`${props.data.checkInDate} 23:59:59`);
  const currentDate = dayjs(`${dayjs().format('YYYY-MM-DD')} 23:59:59`);
  return currentDate.diff(checkInDate, 'day') >= 0;
};

// 接受订单
const handleAccept = async () => {
  try {
    await acceptOrder({
      orderNo: props.data.orderNo,
    });
    upOrderData();
    message.success('操作成功');
  } catch (error) {
    console.error('接受订单失败：', error);
  }
};

// 拒绝订单
const handleRefuse = () => {
  Modal.confirm({
    title: '是否确定拒绝该订单？',
    content: '请优先联系客人说明情况后，再拒绝订单！',
    okText: '确认拒绝',
    cancelText: '取消',
    onOk: async () => {
      try {
        await orderReject({
          orderNo: props.data.orderNo,
          reason: '已联系客人说明原因，带您带来了不便请谅解',
        });
        upOrderData();
        message.success('操作成功');
      } catch (error) {
        console.error('入住确认失败：', error);
      }
    },
  });
};

// 同意修改
const handleAgreeEdit = async () => {
  try {
    await approveEarlyCheckOut({
      orderNo: props.data.orderNo,
    });
    upOrderData();
    message.success('操作成功');
  } catch (error) {
    console.error('接受订单失败：', error);
  }
};

// 点击复制内容
const copy = (content: string) => {
  const input = document.createElement('input');
  input.value = content;
  document.body.append(input);
  input.select();
  document.execCommand('copy');
  input.remove();
  message.success('复制成功');
};
</script>

<template>
  <div class="relative flex min-h-[100%] flex-col">
    <!-- 没有订单id和数据的情况 -->
    <div
      v-if="!data?.orderNo && total === 0"
      class="card-box flex flex-auto flex-col items-center rounded-none border-none pt-[100px]"
    >
      <img :src="`${BASE_ICON_URL}no-data.png`" class="h-auto w-[200px]" />
      <div class="mt-3 opacity-60">
        {{ tabState === 1 ? '暂无未处理订单' : '请选择订单' }}
      </div>
    </div>
    <!-- 有订单id以及相关详情数据的情况 -->
    <template v-else>
      <div
        class="card-box flex min-h-[100vh] flex-col rounded-none border-none px-4 pb-6"
      >
        <!-- 详情头部相关按钮 -->
        <div
          class="card-box sticky top-0 z-[12] min-h-[60px] w-full rounded-none border-x-0 border-t-0 py-3"
        >
          <div class="flex items-center justify-between">
            <Tooltip title="点击复制">
              <p
                class="cursor-pointer pr-1 text-2xl font-bold hover:bg-gray-100"
                @click="copy(data.orderNo)"
              >
                {{ data.orderNo }}
              </p>
            </Tooltip>
            <div class="flex flex-wrap items-center">
              <p v-if="data.orderStatus === 4">已入住</p>
              <p v-else-if="data.orderStatus === 5">已完成</p>
              <p v-else-if="data.orderType === 4">
                {{ data.applyStatus === 4 ? '申请取消' : '已取消' }}
              </p>
              <p v-else-if="data.orderStatus === 3">已接单</p>
              <p v-else-if="data.orderStatus === 2">待接单</p>
              <p v-else-if="data.orderStatus === 1 && data.payStatus === 0">
                等待用户支付
              </p>
              <template v-if="data.orderStatus === 2 && !data.applyStatus">
                <!-- 这是新订单或者续租订单接单按钮 -->
                <Button
                  v-if="data.orderStatus === 2"
                  class="ml-2 h-auto w-auto rounded-none px-10 py-1.5"
                  type="primary"
                  @click="handleAccept"
                >
                  <span>接受</span>
                </Button>
                <Button
                  v-if="data.orderStatus === 2"
                  class="ml-2 h-auto w-auto rounded-none px-10 py-1.5"
                  @click="handleRefuse"
                >
                  <span>拒绝</span>
                </Button>
              </template>
              <!-- 已入住按钮，如果没到入住当天时间则不显示该按钮，防止被误触 -->
              <template v-else>
                <Button
                  v-if="
                    data.orderStatus === 3 &&
                    ![1, 4].includes(data.applyStatus) &&
                    isShowCheckInBtn()
                  "
                  class="ml-2 h-auto w-auto rounded-none px-9 py-1.5"
                  type="primary"
                  @click="handleCheckIn"
                >
                  <span>已入住</span>
                </Button>
                <!-- 一般是过时取消订单的按钮 -->
                <Button
                  v-if="
                    data.applyStatus === 4 &&
                    [2, 3, 4, 5].includes(data.orderStatus)
                  "
                  class="ml-2 h-auto w-auto rounded-none px-7 py-1.5"
                  type="primary"
                  @click="isShowAgreeCancelModal = true"
                >
                  <span>同意取消</span>
                </Button>
                <Button
                  v-if="
                    data.applyStatus === 4 &&
                    [2, 3, 4, 5].includes(data.orderStatus)
                  "
                  class="ml-2 h-auto w-auto rounded-none px-7 py-1.5"
                  @click="isShowRefuseCancelModal = true"
                >
                  <span>拒绝取消</span>
                </Button>
                <!-- 同意用户提交的修改订单 -->
                <Button
                  v-if="
                    data.applyStatus === 1 &&
                    [2, 3, 4].includes(data.orderStatus)
                  "
                  class="ml-2 h-auto w-auto rounded-none px-7 py-1.5"
                  type="primary"
                  @click="handleAgreeEdit"
                >
                  <span>同意修改</span>
                </Button>
                <Button
                  v-if="
                    data.applyStatus === 1 &&
                    [2, 3, 4].includes(data.orderStatus)
                  "
                  class="ml-2 h-auto w-auto rounded-none px-7 py-1.5"
                  @click="isShowRefuseEditModal = true"
                >
                  <span>拒绝修改</span>
                </Button>
              </template>
            </div>
          </div>
          <div class="mt-2 flex items-center">
            <span
              :class="[orderStatus('bg')]"
              class="mr-2 rounded-sm px-1.5 py-0.5 text-xs text-white"
            >
              {{ orderStatus('text') }}
            </span>
          </div>
        </div>
        <!-- 主要是一些详情页面的展示数据内容 -->
        <OrderDetailsMain :data="data" :type="type" />
      </div>
    </template>
    <!-- 拒绝取消的弹窗 -->
    <RefuseCancelModal
      v-model:show="isShowRefuseCancelModal"
      :order-no="data.orderNo"
      @up-order-data="upOrderData"
    />
    <!-- 拒绝修改 -->
    <RefuseEditModal
      v-model:show="isShowRefuseEditModal"
      :order-no="data.orderNo"
      @up-order-data="upOrderData"
    />
    <!-- 同意取消订单弹窗 -->
    <AgreeCancelModal
      v-model:show="isShowAgreeCancelModal"
      :order-no="data.orderNo"
      :refund-amount="data.refundAmount"
      @up-order-data="upOrderData"
    />
  </div>
</template>

<style scoped lang="scss"></style>
